<?php

namespace app\shop\controller;

use think\facade\Db;

class JinjianWxpay extends Base
{
    public function getInitData()
    {
        $shop_id = self::$shop['id'];
        $agent_id = Db::name('shop')
            ->where('id', $shop_id)
            ->value('agent_id');
        $agent = Db::name('agent')
            ->where('id', $agent_id)
            ->find();

        $subject_type = input('subject_type', '', 'trim');
        $serverArr = Db::name('server')
            ->where('type', 'wxpay')
            ->field('id,title as text,config')
            ->select()->each(function ($item) {
                $config = @json_decode($item['config'], true);
                $item['mch_id'] = isset($config['mch_id']) ? $config['mch_id'] : '';
                unset($item['config']);
                return $item;
            });
        $tradeArr = Db::name('jinjian_wxpay_trade')
            ->where('subject_type', $subject_type)
            ->field('settlement_id,rate,trade,desc')
            ->select()->each(function ($item) {
                $item['text'] = $item['trade'] . '（' . $item['rate'] . '）';
                return $item;
            });
        $cityArr = $this->getCityList();
        $bankArr = Db::name('jinjian_wxpay_bank')
            ->column('title');

        return successJson([
            'serverArr' => $serverArr,
            'tradeArr' => $tradeArr,
            'cityArr' => $cityArr,
            'rateMin' => $agent['rate_shop'] ? $agent['rate_shop'] : 60,
            'rateMax' => 60,
            'bankArr' => $bankArr
        ]);

    }

    /**
     * @return string
     * 上传图片
     */
    public function uploadImage()
    {
        $content = input('content', '', 'trim');
        $path = $this->saveBase64Image($content);
        if (!$path) {
            return errorJson('上传失败，请重试！');
        }
        // 压缩图片
        $filepath = '.' . $path;
        \think\Image::open($filepath)->thumb(1200, 1200)->save($filepath);

        return successJson([
            'path' => mediaUrl($path)
        ]);
    }

    /**
     * @return string
     * 上传营业执照
     */
    public function uploadYYzz()
    {
        $content = input('content', '', 'trim');
        $path = $this->saveBase64Image($content);
        if (!$path) {
            return errorJson('上传失败，请重试！');
        }
        // 压缩图片
        $filepath = '.' . $path;
        \think\Image::open($filepath)->thumb(1500, 1500)->save($filepath);
        // OCR识别
        $content = base64_encode(file_get_contents($filepath));
        $ocrResult = $this->yyzzOcr($content);
        $return = [
            'path' => mediaUrl($path)
        ];
        $return = array_merge($return, $ocrResult);

        return successJson($return);
    }


    /**
     * @return string
     * 上传身份证
     */
    public function uploadSfz()
    {
        $content = input('content', '', 'trim');
        $path = $this->saveBase64Image($content);
        if (!$path) {
            return errorJson('上传失败，请重试！');
        }
        // 压缩图片
        $filepath = '.' . $path;
        \think\Image::open($filepath)->thumb(1200, 1200)->save($filepath);
        // OCR识别
        $content = base64_encode(file_get_contents($filepath));
        $ocrResult = $this->sfzOcr($content);
        $return = [
            'path' => mediaUrl($path)
        ];
        $return = array_merge($return, $ocrResult);

        return successJson($return);
    }

    /**
     * @param $content
     * @return string
     */
    private function saveBase64Image($content)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result)) {
            $type = $result[2];
            $dir = './upload/image/';
            if (!file_exists($dir)) {
                mkdir($dir, 0755, true);
            }
            if ($type == 'jpeg') {
                $type = 'jpg';
            }
            $path = $dir . uniqid() . '.' . $type;
            if (file_put_contents($path, base64_decode(str_replace($result[1], '', $content)))) {
                return str_replace('./', '/', $path);
            } else {
                return '';
            }
        } else {
            return '';
        }
    }

    /**
     * 营业执照ocr
     */
    private function yyzzocr($content)
    {
        $result = [
            'name' => '',
            'number' => '',
            'address_code' => '',
            'province' => '',
            'city' => '',
            'region' => '',
            'address' => '',
            'legal_person' => '',
            'time_start' => '',
            'time_end' => '',
        ];
        /*if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result)) {
            $image = str_replace($result[1], '', $content);
            $image = urlencode($image);
            $image_type = '0';
        }*/
        $image = urlencode($content);
        $image_type = '0';
        if ($image) {
            $setting = getSystemSetting('jinjian');
            if (!empty($setting['yyzz_appcode'])) {
                $appCode = $setting['yyzz_appcode'];
            } else {
                return $result;
            }
            $apiUrl = 'https://businessid.market.alicloudapi.com/ai_business_license/v1';
            $headers = [
                "Authorization:APPCODE " . $appCode,
                "Content-Type:application/x-www-form-urlencoded; charset=UTF-8"
            ];
            $bodys = "IMAGE=" . $image . "&IMAGE_TYPE=" . $image_type;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($curl, CURLOPT_URL, $apiUrl);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
            $res = curl_exec($curl);


            $res = json_decode($res, true);

            $res = $res['营业执照识别实体信息'];
            $result = [
                'name' => $res['企业名称'],
                'number' => $res['企业统一社会信用编码'],
                'address_code' => $res['企业所在地国家行政编码'],
                'province' => $res['企业所在省份'],
                'city' => $res['企业所在城市'],
                'region' => $res['企业所在区域'],
                'address' => $res['企业注册地址'],
                'legal_person' => $res['企业法人'],
                'time_start' => $res['企业注册时间'],
                'time_end' => $res['企业营业期限结束时间'] == '无' ? '' : $res['企业营业期限结束时间']
            ];
        }

        return $result;
    }

    /**
     * 身份证ocr
     */
    private function sfzocr($content)
    {
        $result = [
            'name' => '',
            'idcard' => '',
            'valid_time_start' => '',
            'valid_time_end' => ''
        ];
        /*if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result)) {
            $image = str_replace($result[1], '', $content);
            $image = urlencode($image);
            $image_type = '0';
        }*/
        $image = urlencode($content);
        $image_type = '0';
        if ($image) {
            $setting = getSystemSetting('jinjian');
            if (!empty($setting['sfz_appcode'])) {
                $appCode = $setting['sfz_appcode'];
            } else {
                return $result;
            }
            $apiUrl = 'https://aiperson.market.alicloudapi.com/ai_market/ai_ocr_universal/shen_fen_zheng/v1';
            $headers = [
                "Authorization:APPCODE " . $appCode,
                "Content-Type:application/x-www-form-urlencoded; charset=UTF-8"
            ];
            $bodys = "IMAGE=" . $image . "&IMAGE_TYPE=" . $image_type;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($curl, CURLOPT_URL, $apiUrl);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
            $res = curl_exec($curl);
            $res = json_decode($res, true);

            $res = $res['身份证识别实体信息'];
            $rxm = $res['身份证人像面实体信息'];
            $ghm = $res['身份证国徽面实体信息'];
            $result = [
                'name' => $rxm['姓名'],
                // 'sex' => $rxm['性别'],
                // 'birthday' => $rxm['出生日期'],
                // 'minzu' => $rxm['民族'],
                // 'address' => $rxm['住址'],
                'idcard' => $rxm['身份证号'],
                // 'jiguan' => $ghm['签发机关']
            ];
            $validTimeArr = explode('-', $ghm['有效期限']);
            $result['valid_time_start'] = isset($validTimeArr[0]) ? str_replace('.', '-', $validTimeArr[0]) : '';
            $result['valid_time_end'] = isset($validTimeArr[1]) ? str_replace('.', '-', $validTimeArr[1]) : '';
        }

        return $result;
    }

    private function getCityList()
    {
        $list = Db::name('citys')
            ->where('pid', 0)
            ->order('id asc')
            ->field('city_id as value,title as text')
            ->select()
            ->each(function ($item) {
                $item['children'] = Db::name('citys')
                    ->where('pid', $item['value'])
                    ->order('id asc')
                    ->field('city_id as value,title as text')
                    ->select()
                    ->toArray();
                return $item;
            });

        return $list;
    }

    /**
     * 提交进件
     */
    public function doSubmit()
    {
        $shop_id = self::$shop['id'];
        $server_id = input('server_id', 0, 'intval');
        $server_mch_id = input('server_mch_id', '', 'trim');
        $shop = Db::name('shop')
            ->where('id', $shop_id)
            ->find();

        //基础信息
        $settlement_id = input('settlement_id', '', 'trim');
        $qualification_type = input('qualification_type', '', 'trim');
        $qualifications = input('qualifications', '', 'trim');
        $activities_rate = input('activities_rate', '', 'trim');
        if ($activities_rate) {
            $activities_id = '20191030111cff5b5e';
        } else {
            $activities_id = '';
        }
        // 主体资料
        $subject_type = input('subject_type', '', 'trim');
        $license_copy = input('license_copy', '', 'trim');
        $license_number = input('license_number', '', 'trim');
        $merchant_name = input('merchant_name', '', 'trim');
        $legal_person = input('legal_person', '', 'trim');
        $merchant_shortname = input('merchant_shortname', '', 'trim');
        $service_phone = input('service_phone', '', 'trim');
        // 超级管理员资料
        $contact_name = input('legal_person', '', 'trim');
        $contact_id_number = input('id_card_number', '', 'trim');
        $contact_email = input('contact_email', '', 'trim');
        $mobile_phone = input('mobile_phone', '', 'trim');
        // 经营资料
        $sales_scenes_type = input('sales_scenes_type', 'SALES_SCENES_STORE', 'trim');
        $biz_store_name = input('biz_store_name', '', 'trim');
        $biz_address_code = input('biz_address_code', '', 'trim');
        $biz_store_address = input('biz_store_address', '', 'trim');
        $store_entrance_pic = input('store_entrance_pic', '', 'trim');
        $indoor_pic = input('indoor_pic', '', 'trim');
        // 法人身份证件
        $id_doc_type = input('id_doc_type', 'IDENTIFICATION_TYPE_IDCARD', 'trim');
        $id_card_copy = input('id_card_copy', '', 'trim');
        $id_card_national = input('id_card_national', '', 'trim');
        $id_card_name = input('id_card_name', '', 'trim');
        $id_card_number = input('id_card_number', '', 'trim');
        $card_period_begin = input('card_period_begin', '', 'trim');
        $card_period_end = input('card_period_end', '', 'trim');
        $owner = input('owner', true);
        // 银行卡资料
        $bank_account_type = input('bank_account_type', 'BANK_ACCOUNT_TYPE_CORPORATE', 'trim');
        $account_name = input('account_name', '', 'trim');
        $account_bank = input('account_bank', '', 'trim');
        $bank_name = input('bank_name', '', 'trim');
        if ($account_bank != '其他银行') {
            $bank_name = '';
        }
        $bank_address_code = input('bank_address_code', '', 'trim');
        $account_number = input('account_number', '', 'trim');
        // 其他字段（非进件需要）
        $server_name = input('server_name', '', 'trim');
        $trade_title = input('trade_title', '', 'trim');
        $trade_rate = input('trade_rate', '', 'trim');
        $qualifications_desc = input('qualifications_desc', '', 'trim');
        $store_city = input('store_city', '', 'trim');
        $bank_city = input('bank_city', '', 'trim');

        $data = [];
        // 基础信息
        $data['server_mch_id'] = $server_mch_id;
        $data['qualification_type'] = $qualification_type;
        $data['qualifications'] = $qualifications;
        $data['settlement_id'] = $settlement_id;
        $data['activities_id'] = $activities_id;
        $data['activities_rate'] = $activities_rate;
        // 主体资料
        $data['subject_type'] = $subject_type;
        $data['license_copy'] = $license_copy;
        $data['license_number'] = $license_number;
        $data['merchant_name'] = $merchant_name;
        $data['legal_person'] = $legal_person;
        $data['merchant_shortname'] = $merchant_shortname;
        $data['service_phone'] = $service_phone;
        // 超级管理员资料
        $data['contact_name'] = $contact_name;
        $data['contact_id_number'] = $contact_id_number;
        $data['contact_email'] = $contact_email;
        $data['mobile_phone'] = $mobile_phone;
        // 经营资料
        $data['sales_scenes_type'] = $sales_scenes_type;
        $data['biz_store_name'] = $biz_store_name;
        $data['biz_address_code'] = $biz_address_code;
        $data['biz_store_address'] = $biz_store_address;
        $data['store_entrance_pic'] = $store_entrance_pic;
        $data['indoor_pic'] = $indoor_pic;
        // 法人身份证件资料
        $data['id_doc_type'] = $id_doc_type;
        $data['id_card_copy'] = $id_card_copy;
        $data['id_card_national'] = $id_card_national;
        $data['id_card_name'] = $id_card_name;
        $data['id_card_number'] = $id_card_number;
        $data['card_period_begin'] = $card_period_begin;
        $data['card_period_end'] = $card_period_end;
        $data['owner'] = $owner;
        // 银行卡资料
        $data['bank_account_type'] = $bank_account_type;
        $data['account_name'] = $account_name;
        $data['account_bank'] = $account_bank;
        $data['bank_name'] = $bank_name;
        $data['bank_address_code'] = $bank_address_code;
        $data['account_number'] = $account_number;

        // 验证字段
        if (!$license_copy) {
            return errorJson('请上传营业执照');
        }
        if (!$id_card_copy) {
            return errorJson('请上传身份证人像面');
        }
        if (!$id_card_national) {
            return errorJson('请上传身份证国徽面');
        }
        if (!$store_entrance_pic) {
            return errorJson('请上传门店门头照片');
        }
        if (!$indoor_pic) {
            return errorJson('请上传店内环境照片');
        }

        $info = Db::name('jinjian_wxpay')
            ->where('shop_id', $shop_id)
            ->find();
        $saveData = $data;
        $saveData['shop_id'] = $shop_id;
        $saveData['server_id'] = $server_id;
        $saveData['agent_id'] = $shop['agent_id'];
        $saveData['server_mch_id'] = $server_mch_id;
        $saveData['ext'] = json_encode([
            'server_name' => $server_name,
            'trade_title' => $trade_title,
            'trade_rate' => $trade_rate,
            'qualifications_desc' => $qualifications_desc,
            'store_city' => $store_city,
            'bank_city' => $bank_city,
        ]);
        $saveData['add_time'] = time();
        if ($info) {
            Db::name('jinjian_wxpay')
                ->where('shop_id', $shop_id)
                ->update($saveData);
        } else {
            Db::name('jinjian_wxpay')
                ->insert($saveData);
        }
        // 上传各图片，获取MediaID
        $WechatClass = $this->newWechat($server_id);

        $license_copy = $this->uploadToWx($WechatClass, $license_copy);
        if (!$license_copy) {
            return errorJson('营业执照图片格式错误，请重新上传');
        }
        $data['license_copy'] = $license_copy;

        $id_card_copy = $this->uploadToWx($WechatClass, $id_card_copy);
        if (!$id_card_copy) {
            return errorJson('身份证人像面照片格式错误，请重新上传');
        }
        $data['id_card_copy'] = $id_card_copy;

        $id_card_national = $this->uploadToWx($WechatClass, $id_card_national);
        if (!$id_card_national) {
            return errorJson('身份证国徽面照片格式错误，请重新上传');
        }
        $data['id_card_national'] = $id_card_national;

        $store_entrance_pic = $this->uploadToWx($WechatClass, $store_entrance_pic);
        if (!$store_entrance_pic) {
            return errorJson('门店门头照片格式错误，请重新上传');
        }
        $data['store_entrance_pic'] = $store_entrance_pic;

        $indoor_pic = $this->uploadToWx($WechatClass, $indoor_pic);
        if (!$indoor_pic) {
            return errorJson('店内环境照片格式错误，请重新上传');
        }
        $data['indoor_pic'] = $indoor_pic;

        if ($qualifications) {
            $arr = explode(',', $qualifications);
            $mediaArr = [];
            foreach ($arr as $v) {
                $mediaId = $this->uploadToWx($WechatClass, $v);
                if (!$mediaId) {
                    return errorJson('特殊资质图片格式错误，请重新上传');
                }
                $mediaArr[] = $mediaId;
            }
            $data['qualifications'] = $mediaArr;
        }

        // 生成申请单号
        $business_code = $WechatClass->getBusinessCode();
        $data['business_code'] = $business_code;

        // 提交入驻申请
        if (!file_exists($WechatClass->publicKeyAddr)) {
            $WechatClass->get_Certificates();
        }
        $rs = $WechatClass->applyEnterv3($data);
        if ($rs['errno']) {
            return errorJson('错误：' . $rs['message']);
        } else {
            Db::name('jinjian_wxpay')
                ->where('shop_id', $shop_id)
                ->update([
                    'business_code' => $business_code,
                    'applyment_id' => $rs['applyment_id'],
                    'applyment_state' => 'APPLYMENT_STATE_AUDITING',
                    'applyment_state_msg' => '审核中',
                    'sub_mchid' => '',
                    'sign_url' => '',
                    'audit_detail' => '',
                    'update_time' => time()
                ]);
            return successJson([
                'applyment_id' => $rs['applyment_id'],
                'business_code' => $business_code
            ], '提交成功，请等待审核');
        }
    }

    /**
     * 上传图片到微信，返回media_id
     */
    public function uploadToWx($WechatClass, $path)
    {
        $path = realpath('.' . $path);
        $rs = $WechatClass->uploadImage($path);
        return $rs['media_id'];
    }

    /**
     * 初始化微信进件类
     */
    private function newWechat($server_id)
    {
        $config = Db::name('server')
            ->where('id', $server_id)
            ->value('config');
        $config = json_decode($config, true);

        $option = [
            'appid' => $config['appid'],
            'secret' => $config['appsecret'],
            'mch_id' => $config['mch_id'],
            'aes_key' => $config['key'],
            'diy_key' => $config['key'],  //自定义key
            'apiclient_cert' => '.' . mediaUrl($config['apiclient_cert']),
            'apiclient_key' => '.' . mediaUrl($config['apiclient_key'])
        ];
        return new \Wxpay\jinjian\Wechat($option);
    }

    public function getLastForm()
    {
        $shop_id = self::$shop['id'];
        $subject_type = input('subject_type', '', 'trim');
        $shop = Db::name('shop')
            ->where([
                'id' => $shop_id
            ])
            ->find();
        if (!$shop) {
            return errorJson('商户不存在，请刷新页面重试');
        }
        $info = Db::name('jinjian_wxpay')
            ->where([
                'shop_id' => $shop_id,
                'subject_type' => $subject_type
            ])
            ->find();
        if (!$info) {
            return successJson([
                'form' => null,
                'ext' => null
            ]);
        }
        unset($info['id'], $info['agent_id'], $info['business_code'], $info['activities_id'], $info['applyment_id'], $info['applyment_state'], $info['applyment_state_msg'], $info['sub_mchid'], $info['sign_url'], $info['audit_detail'], $info['add_time']);
        if ($info['qualifications']) {
            $info['qualifications'] = explode(',', $info['qualifications']);
        } else {
            $info['qualifications'] = [];
        }
        $ext = $info['ext'] ? json_decode($info['ext'], true) : null;
        unset($info['ext']);
        return successJson([
            'form' => $info,
            'ext' => $ext
        ]);
    }

    /**
     * 获取进件申请单状态
     */
    public function getApplyResult()
    {
        $refresh = input('refresh', 0, 'intval');
        $shop_id = self::$shop['id'];
        $shop = Db::name('shop')
            ->where([
                'id' => $shop_id
            ])
            ->find();
        if (!$shop) {
            return errorJson('商户不存在，请刷新页面重试');
        }
        if ($refresh) {
            $this->flushApplyStatus($shop_id);
        }
        $info = Db::name('jinjian_wxpay')
            ->where('shop_id', $shop_id)
            ->field('subject_type,settlement_id,activities_rate,applyment_state,applyment_state_msg,sub_mchid,sign_url,audit_detail,update_time,add_time')
            ->find();
        if (!$info) {
            return errorJson('没有找到进件记录');
        }
        $info['add_time'] = date('Y-m-d H:i:s', $info['add_time']);
        $info['update_time'] = date('Y-m-d H:i:s', $info['update_time']);
        if ($info['applyment_state'] == 'APPLYMENT_STATE_FINISHED') {
            // 获取费率
            if ($info['activities_rate']) {
                $rate = $info['activities_rate'] . '%';
            } else {
                $rate = Db::name('jinjian_wxpay_trade')
                    ->where('settlement_id', $info['settlement_id'])
                    ->value('rate');
            }
            $info['rate'] = $rate;
        }
        if ($info['applyment_state'] == 'APPLYMENT_STATE_REJECTED' && $info['audit_detail']) {
            // 获取费率
            $info['audit_detail'] = json_decode($info['audit_detail'], true);
        }
        unset($info['settlement_id'], $info['activities_rate']);

        return successJson($info);
    }

    /**
     * 查询申请单状态
     */
    private function flushApplyStatus($shop_id)
    {
        $info = Db::name('jinjian_wxpay')
            ->where('shop_id', $shop_id)
            ->find();
        if (!$info || empty($info['applyment_id'])) {
            return errorJson('刷新失败，没有找到进件记录');
        }
        $WechatClass = $this->newWechat($info['server_id']);
        $result = $WechatClass->enquiryOfApplyStatus(['applyment_id' => $info['applyment_id']]);
        Db::name('jinjian_wxpay')
            ->where('applyment_id', $info['applyment_id'])
            ->update([
                'applyment_state' => $result['applyment_state'],
                'applyment_state_msg' => $result['applyment_state_msg'],
                'sub_mchid' => isset($result['sub_mchid']) ? $result['sub_mchid'] : '',
                'audit_detail' => isset($result['audit_detail']) ? json_encode($result['audit_detail']) : '',
                'sign_url' => isset($result['audit_detail']) ? $result['sign_url'] : '',
                'update_time' => time()
            ]);
        if (empty($info['sub_mchid']) && !empty($result['sub_mchid'])) {
            // {"wxpay_status":1,"wxpay_type":"server","wxpay_server_id":4,"wxpay_mch_id":"123123123","wxpay_rate":"0.38"}
            // 获取费率
            if ($info['activities_rate']) {
                $rate = $info['activities_rate'] . '%';
            } else {
                $rate = Db::name('jinjian_wxpay_trade')
                    ->where('settlement_id', $info['settlement_id'])
                    ->value('rate');
            }

            Db::name('shop')
                ->where('id', $info['shop_id'])
                ->update([
                    'wxpay_config' => json_encode([
                        'wxpay_status' => 1,
                        'wxpay_type' => 'server',
                        'wxpay_server_id' => $info['server_id'],
                        'wxpay_mch_id' => $result['sub_mchid'],
                        'wxpay_rate' => str_replace('%', '', $rate)
                    ])
                ]);
        }
        // echo '最新状态：' . $result['applyment_state'];
    }
}
